<?php
namespace app\common\model;
use app\common\traits\Models;
use think\Model;
use think\Db;
use think\facade\{
    App,Request,Config
};
class ArticleCat extends Model
{
    use Models;
    protected $readonly = [];
    protected $auto     = [];
    protected $insert   = [];
    protected $update   = [];
//获取器====================================================================================//
    public function getCreateTimeAttr($value)
    {
        return com_time_format($value);
    }
    public function getUpdateTimeAttr($value)
    {
        return com_time_format($value);
    }
/*关联模型=================================================================================*/
   	public function article()
    {
        return $this->hasMany('article','cat_id','id');
    }
    /**
     * 返回分类下的所有子分类,  无限极没有分页, 重新组装数据结构, 有分类的深度
     * @param number $id 分类id
     */
    public static function allSubCat($id = 0){
        static $temp = [];
        $rs = Db::name('article_cat')->where('parent_id', $id)->order('sort','desc')->select();
        foreach($rs as $val){
            $val['depath'] = substr_count($val['cat_tree'], ",")-1;
            $temp[] = $val;
            self::allSubCat($val['id']);
        }
        return $temp;
    }

    /**
     * 创建自己的树结构
     * @param number $parent_id 父ID
     * @return string 树结构
     */
    public static function buildTree($parent_id = 0){
        $temp = ",0,";
        if( $parent_id!=0 ){
            $temp = Db::name('article_cat')->where("id",$parent_id)->value("cat_tree").$parent_id.",";
        }
        return $temp;
    }

    /**
     * 删除
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function del($id){
        if(!is_array($id)) $id = [$id];
        foreach($id as $v){
            if(!$this->checkDel($v)) return false;
            $this::destroy(function($query)use($v){
                $query->where('id',$v);
            },true);
        }
        return true;
    }

    /**
     * 验证是否可能删除分类
     * @param unknown $id  分类id
     * @return true(可以删除) or false;
     */
    public function checkDel($id){
       if( Db::name('article_cat')->where('parent_id', $id)->find() ){
            $this->error = '分类下有子分类，不能删除!';
            return false;
       }

       if( Db::name('article')->where('cat_id', $id)->find() ){
            $this->error = '分类下有文章，不能删除!';
            return false;
       }
       return true;
    }
}
